//
//  RespiratoryRateViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-26.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "RespiratoryRateViewController.h"
#import "BasicSignsCell.h"
#import "EditImportSignsViewController.h"
@interface RespiratoryRateViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
/**
 *  呼吸速率tableView显示
 */
@property (strong, nonatomic) IBOutlet UITableView *respiratoryRateTableView;
/**
 *  上传的字典
 */
@property (nonatomic, strong) NSMutableDictionary *uploadDic;
@end

@implementation RespiratoryRateViewController

- (NSMutableDictionary *)uploadDic{
    if (_uploadDic == nil) {
        self.uploadDic = [NSMutableDictionary dictionary];
    }
    return _uploadDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.respiratoryRateTableView.delegate = self;
    self.respiratoryRateTableView.dataSource = self;
    [self  setNaviBarAttribute];
    self.respiratoryRateTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.navigationItem.title = @"呼吸速率";
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.translucent = NO;
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 30, 23);
    //    [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
    [rightButton setTitle:@"添加" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction{
    if ([self getCellTextFieldText]) {
        [self _parsePersonalDataSource:kBaseURL];
    }
}



#pragma mark - tableView的代理方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }else{
        return 1;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 20;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 54;
    }else{
        return 44;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BasicSignsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"basicSignsCell"];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BasicSignsCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BasicSignsCell" owner:self options:nil] firstObject];
        }
    }
    if(indexPath.section == 0){
        cell.signsDataTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        cell.signsDataTextField.delegate = self;
        if (indexPath.row == 0) {
            cell.signsTypeLabel.text = @"日期";
            cell.signsDataTextField.enabled = NO;
            cell.signsDataTextField.text = self.timeStr;
            cell.jumpImageView.hidden = YES;
        }else{
            cell.signsTypeLabel.text = @"次/分";
            [cell.signsDataTextField becomeFirstResponder];
            UILabel *label = [[UILabel alloc] init];
            if (kScreenWidth == 414) {
                label.frame = CGRectMake(0, 0, 36, 18);
            }else{
                label.frame = CGRectMake(0, 0, 31, 18);
            }
            label.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
            label.text = @"次/分";
            label.textColor = [UIColor lightGrayColor];
            cell.signsDataTextField.rightView = label;
            cell.signsDataTextField.rightViewMode = UITextFieldViewModeAlways;
            
            cell.signsDataTextField.text = @"";
            cell.jumpImageView.hidden = YES;
        }
    }else if (indexPath.section == 1){
        cell.signsDataTextField.text = @"";
        cell.signsDataTextField.enabled = NO;
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        EditImportSignsViewController *editImportSignsVC = [[EditImportSignsViewController alloc] init];
        editImportSignsVC.naviTitleStr = self.navigationItem.title;
        [self.navigationController pushViewController:editImportSignsVC animated:YES];
    }
}



#pragma mark - 网路数据上传 -
- (void)_parsePersonalDataSource:(NSString *)urlString{
    [self showActionView];
    NSString *time = [self setNewTime];
    
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/logadd/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [self.uploadDic setValue:kPlatform forKey:@"platform"];
    [self.uploadDic setValue:kVersion forKey:@"version"];
    [self.uploadDic setValue:@"6" forKey:@"type"];
    [self.uploadDic setValue:time forKey:@"daytime"];
    [manager POST:postURL parameters:self.uploadDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:@"上传失败"];
        }else{
            MyNSLog("========%@========", [responseObject objectForKey:@"msg"]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];
}


#pragma mark - 获取cell中的textField -
- (BOOL)getCellTextFieldText{
    NSIndexPath *pathOne=[NSIndexPath indexPathForRow:1 inSection:0];//获取cell的位置
    BasicSignsCell *cellOne= (BasicSignsCell *)[self.respiratoryRateTableView cellForRowAtIndexPath: pathOne];
    
    if ([cellOne.signsDataTextField.text floatValue] > 50 || [cellOne.signsDataTextField.text floatValue] < 0) {
        alertContent(@"呼吸速率范围在0-50次/分");
        cellOne.signsDataTextField.text = @"";
        return NO;
    }else{
        [self.uploadDic setValue:cellOne.signsDataTextField.text forKey:@"respiration"];
        return YES;
    }
    
}

#pragma mark - 获取当前的时间 -
- (NSString *)setNewTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[formatter stringFromDate: [NSDate date]];
    return locationString;
    
}
//- (NSString *)setNewTime{
//    NSDate *now = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
//    int year = [dateComponent year];
//    int month = [dateComponent month];
//    int day = [dateComponent day];
//    
//    NSString *time = [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
//    MyNSLog("%@",time);
//    return time;
//}
#pragma mark - textField的代理方法 -
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    //用户结束输入
    [textField resignFirstResponder];
    
    return YES;
}

//textField.text 输入之前的值         string 输入的字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string   // return NO to not change text
{
    
    BasicSignsCell *cell = nil;
    UIView  *view = textField.superview;
    for (NSInteger i = 0; i < 1; ) {
        if ([view isKindOfClass:[BasicSignsCell class]]) {
            cell = (BasicSignsCell *)view;
            break;
        }else{
            view =view.superview;
        }
    }
    //的情况才行，如果是删除的时候，string.length==0
    NSInteger length = (NSInteger)cell.signsDataTextField.text.length;
    if (length >= 2  &&  string.length >0)
    {
        return  NO;
    }
    
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        //首字母不能为0和小数点
        if([cell.signsDataTextField.text length]==0){
            if (single == '0') {
                MyNSLog("亲，第一个数字不能为0");
                [cell.signsDataTextField.text stringByReplacingCharactersInRange:range withString:@""];
                return NO;
            }
            
        }
    }
    
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
    NSString *filtered =
    [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    BOOL basic = [string isEqualToString:filtered];
    return basic;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
